package com.meatball.iot.common.mqtt

import com.meatball.iot.common.ClientConnectionThreadPool
import com.meatball.iot.common.mqtt.enums.MqttStrangelyEnum
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken
import org.eclipse.paho.client.mqttv3.MqttCallback
import org.eclipse.paho.client.mqttv3.MqttMessage
import org.slf4j.LoggerFactory

class PushCallback : MqttCallback {
    companion object {
        private val logger = LoggerFactory.getLogger(PushCallback::class.java)
    }

    /**
     * 创建一个固定大小的线程池，用于处理客户端连接
     */
    private val executorService = ClientConnectionThreadPool.executorService()

    override fun connectionLost(p0: Throwable?) {
        // 连接丢失后，一般在这里面进行重连
        logger.info("断开连接，可以重新连接。")
    }

    override fun messageArrived(topic: String?, message: MqttMessage?) {
        // subscribe后得到的消息会执行到这里面
        logger.info("接收消息主题：$topic")
        logger.info("接收到消息Qos：${message?.qos}")
        if (message != null && topic != null) {
            val msg = message.payloadAsString
            logger.info("接收消息内容：$msg")
            executorService.execute {
                val type = topic.split("/")[0]
                StrategyFactory().getMqttStrategy(MqttStrangelyEnum.fromCode(type))
                    .toStart(msg, topic)
            }
        }
    }

    override fun deliveryComplete(token: IMqttDeliveryToken?) {
        logger.info("消息投递完成，令牌为：${token?.response}")
    }

    /**
     * 扩展函数，用于获取 MqttMessage 的消息内容字符串表示
     */
    private val MqttMessage.payloadAsString: String
        get() = String(payload, Charsets.UTF_8)
}